import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacpp.opencv_imgproc;
import org.bytedeco.javacpp.opencv_objdetect;
import org.bytedeco.javacv.*;

import javax.swing.*;
import java.io.File;

import static org.bytedeco.javacpp.opencv_imgproc.COLOR_BGRA2GRAY;

public class App1 {
    public static void main(String args[]) throws Exception{
        OpenCVFrameGrabber grabber = OpenCVFrameGrabber.createDefault(0);
        grabber.start();
        showFramesWithFace("Video", grabber);
        grabber.stop();
        grabber.close();
    }

    private static void showFramesWithFace(String winTitle, FrameGrabber grabber) throws FrameGrabber.Exception, InterruptedException {
        OpenCVFrameConverter.ToMat convertToMat = new OpenCVFrameConverter.ToMat();
        String path = "H:\\openCV\\face\\src\\main\\resources\\haarcascade_frontalface_alt.xml" ;

        File fileAbsolutePath = new File(path);
        //opencv_objdetect.CvHaarClassifierCascade face_cascade=opencv_objdetect.cvLoadHaarClassifierCascade(fileAbsolutePath.getAbsolutePath(),new opencv_core.CvSize(0,0));
        opencv_objdetect.CascadeClassifier face_cascade = new opencv_objdetect.CascadeClassifier(fileAbsolutePath.getAbsolutePath());
        opencv_core.RectVector faces = new opencv_core.RectVector();
        CanvasFrame canvas = new CanvasFrame(winTitle,1);//新建一个窗口
        canvas.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        canvas.setAlwaysOnTop(true);
        while (true) {
            if (!canvas.isVisible()) {
                break;
            }
            Frame frame = grabber.grab();
            opencv_core.Mat mat = convertToMat.convert(frame);
            if (mat.empty())
                continue;
            opencv_core.Mat videoMatGray = new opencv_core.Mat();
            opencv_imgproc.cvtColor(mat, videoMatGray, COLOR_BGRA2GRAY);
            opencv_imgproc.equalizeHist(videoMatGray, videoMatGray);
            //int[] rejectLevels = new int[0];
            //double[] levelWeights = new double[0];
            face_cascade.detectMultiScale(videoMatGray, faces);
            for (int i = 0; i < faces.size(); i++) {
                opencv_core.Rect face = faces.get(i);
                opencv_imgproc.rectangle(mat, face, opencv_core.Scalar.RED, 4, 8, 0);
            }

            //opencv_highgui.imshow(winTitle, mat);
            //opencv_highgui.waitKey(30);
            canvas.showImage(convertToMat.convert(mat));
            Thread.sleep(30);//50毫秒刷新一次图像
        }
    }

}
